package com.lagou.job.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.LoadingCache;
import com.lagou.job.common.Constant;
import com.lagou.job.mapper.PositionMapper;
import com.lagou.job.pojo.Position;
import com.lagou.job.service.PositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisCluster;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

/**
 * 职位服务实现类
 * @author yzh
 */
@Service
public class PositionServiceImpl implements PositionService {

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private JedisCluster jedisCluster;

    @Autowired
    private LoadingCache<String, Object> guavaCache;

    @Override
    public List<Position> getHotPositionFromLocalCache() {
        //返回值:热门职位集合
        List<Position> positionHotList = null;
        try {
            //1.首先从本地缓存中获取热门职位集合
            positionHotList = (List<Position>)guavaCache.get(Constant.POSITION_HOT_LIST_CACHE_KEY, new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    //2.如果本地缓存中没有进行回源
                    return getHotPositionFromBySource();
                }
            });
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return positionHotList;
    }

    @Override
    public List<Position> getHotPositionFromBySource() {
        //返回值:热门职位集合
        List<Position> positionHotList = null;
        try {
            //1.首先从Redis中获取热门职位集合
            List<String> positionHotStrList = jedisCluster.lrange(Constant.POSITION_HOT_LIST_CACHE_KEY, 0, -1);
            final List<Position> tempPositionHotList = new ArrayList<>();
            //2.如果集合不为空，遍历集合并封装到返回值中
            if(positionHotStrList != null && positionHotStrList.size() > 0) {
                positionHotStrList.forEach(p -> {
                    tempPositionHotList.add(JSONObject.parseObject(p, Position.class));
                });
                positionHotList = tempPositionHotList;
            } else {//3.如果集合为空，从数据库获取，并回填到Redis中
                //从数据库获取
                positionHotList = positionMapper.getAllPosition();
                //回填到Redis中
                positionHotList.forEach(p -> {
                    jedisCluster.lpush(Constant.POSITION_HOT_LIST_CACHE_KEY, JSONObject.toJSONString(p));
                });
                //设置Redis中key的过期时间 ：设置5秒钟自动失效，保证数据一致性
                jedisCluster.expire(Constant.POSITION_HOT_LIST_CACHE_KEY, 5);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return positionHotList;
    }
}
